﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.App.CIHelper;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using ComicIsland.Common.Entities.ComicDatabase;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views.DownloadComicViews
{
    public partial class DownloadComicList : PhoneApplicationPage
    {
        private bool IsNeedReloadData = false;
        private TableDownloadComic tableDownloadComic = null;
        public DownloadComicList()
        {
            InitializeComponent();
            this.IsNeedReloadData = true;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            this.IsNeedReloadData = false;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            //
            if (base.NavigationContext.QueryString.ContainsKey("TableDownloadComic"))
            {
                string paramDownloadComic = string.Empty;
                base.NavigationContext.QueryString.TryGetValue("TableDownloadComic", out paramDownloadComic);
                if (string.IsNullOrWhiteSpace(paramDownloadComic))
                {
                    base.NavigationService.GoBack();
                    return;
                }
                tableDownloadComic = JSONHelper.Deserialize<TableDownloadComic>(paramDownloadComic);
                if (tableDownloadComic == null)
                {
                    base.NavigationService.GoBack();
                    return;
                }
                if (this.IsNeedReloadData)
                {
                    //新增或更新本地缓存（要下载漫画的缓存列中）
                    //this.InsertOrUpdateLocalCache();
                    //TODO 添加至下载队列中去                    
                }
            }

            //加载下载过的漫画列表
            if (this.IsNeedReloadData)
            {
                LoadDownloadQueueComics();
            }
        }


        /// <summary>
        /// 加载缓存的漫画列表
        /// </summary>
        void LoadDownloadQueueComics()
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                this.llms.ItemsSource = App.comicDbHelper.ComicAllObservableCollection();
            });
        }

        private void gridComic_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            DbComic item = (sender as Grid).DataContext as DbComic;
            if (item == null)
                return;
            string param = string.Concat("?comicId=", item.ComicId);
            NaviService.Navigate(ComicIslandPage.DCVDownloadQueuePage, param);
        }

        private void llms_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void appBarDelete_Click(object sender, EventArgs e)
        {
            if (MessageBoxResult.OK != MessageBox.Show(string.Format("确认删除选中的 {0} 个缓存漫画？", this.llms.SelectedItems.Count), AppResources.ApplicationTitle, MessageBoxButton.OKCancel))
            {
                return;
            }

            var sources = this.llms.ItemsSource as ObservableCollection<DbComic>;
            if (!(sources != null && sources.Count > 0))
                return;

            while (this.llms.SelectedItems.Count > 0)
            {
                var source = this.llms.SelectedItems[0] as DbComic;
                if (source == null)
                    continue;

                try
                {
                    bool result = false;
                    //删除漫画、漫画中的章节、漫画中章节的图片
                    App.comicDbHelper.ImageRemoveByComic(source.ComicId);
                    App.comicDbHelper.ChapterRemoveByComic(source.ComicId);
                    App.comicDbHelper.ComicRemoveByComic(source.ComicId);
                    //TODO 删除数据库信息后，已下载的缓存信息也需要删除
                    //删除数据库信息后，书架也需要删除
                    LocalUserBookStoreAlbumHelper helper = new LocalUserBookStoreAlbumHelper();
                    helper.RemoveComicFromLocalUserBookStoreAlbum(source.ComicId);
                    //
                    sources.Remove(source);
                }
                catch (Exception err)
                {
                    LogHelper.LogInfo(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                }
            }
        }

        private void appBarSelect_Click(object sender, EventArgs e)
        {
            var appBarIcon = sender as ApplicationBarIconButton;
            if (appBarIcon == null)
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                if ("全选".Equals(appBarIcon.Text))
                {
                    appBarIcon.Text = "取消";
                    appBarIcon.IconUri = new Uri("/Images/Icons/uncheckedall.png", UriKind.Relative);
                    this.llms.IsSelectionEnabled = true;
                    foreach (var item in this.llms.ItemsSource)
                    {
                        var container = this.llms.ContainerFromItem(item) as LongListMultiSelectorItem;
                        if (container != null) container.IsSelected = true;
                    }
                }
                else
                {
                    appBarIcon.Text = "全选";
                    appBarIcon.IconUri = new Uri("/Images/Icons/checkedall.png", UriKind.Relative);
                    this.llms.IsSelectionEnabled = false;
                }
            });
        }

    }
}